const getStorage = storage => {
  const remove = key => {
    if (key.endsWith("*")) {
      let keys = Object.keys(storage);
      key = key.slice(0, -1);
      keys.forEach(k => {
        if (k.startsWith(key)) {
          storage.removeItem(k);
        }
      });
    } else {
      storage.removeItem(key);
    }
  };

  const set = (key, value) => {
    return storage.setItem(key, JSON.stringify(value));
  };

  const get = key => {
    let str = storage.getItem(key);
    if (str) {
      return JSON.parse(str);
    }
    return null;
  };

  const clear = () => {
    storage.clear();
  };

  //临时缓存
  const tempClear = () => {
    remove("storage_1_*");
  };

  //长时间缓存
  const longClear = () => {
    remove("storage_2_*");
  };

  return {
    remove,
    set,
    get,
    clear,
    tempClear,
    longClear
  };
};

const session = getStorage(sessionStorage);
const local = getStorage(localStorage);

//t：默认 1，  1 临时缓存  2 长时间缓存  3 永久缓存
const getStorageKey = (k, param = "", t = 1) => {
  let str = JSON.stringify(param);
  return "storage_" + t + "_" + k + "_" + str.replace(/['":, {}]/g, "");
};

export { session, local, getStorageKey };
